package com.effectiv.req1.business.impl;

import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.effectiv.req1.business.api.AbstractBusinessService;
import com.effectiv.req1.business.api.ProjectService;
import com.effectiv.req1.domain.Actor;
import com.effectiv.req1.domain.Company;
import com.effectiv.req1.domain.Project;
import com.effectiv.req1.domain.User;


import com.effectiv.req1.repository.ProjectRepository;
import com.effectiv.req1.repository.UserRepository;
import com.effectiv.req1.security.SecurityUtil;

@Service
@Slf4j
public class ProjectServiceImpl extends AbstractBusinessService<Project,String> implements ProjectService{
	
	@Autowired
	private ProjectRepository repository;
	
	@Autowired
	private UserRepository userRepository;
	
	@Override
	public List<Project> findProjects() {
		List<Project> projects = null;
		Company company = getCompany();
		if (SecurityUtil.isCompanyAdmin()) {
			// show all the projects for the company
			log.info("Find by company");
			projects = repository.findByCompany(company);
		} else {
			// normal user show all the projects where he is a participant
			log.info("Find by company and user");
			projects = repository.findByCompanyAndUsers(company,
					SecurityUtil.getUserDetails());
		}
		return projects;
	}
	
	
	@Override
	public void save(Project t) {
		t.setManager(getUser());
		t.setCompany(getCompany());
		super.save(t);
	}




	@Override
	public Project update(Project t) {
		Project old = findOne(t.getId());
		
		old.setName(t.getName());
		old.setDescription(t.getDescription());
		
		return super.update(old);
	}


	


	@Override
	protected void initInternal() {
		setRepository(repository);		
	}


	@Override
	public Project addUser(String projectId, String userId) {
		Project project = findOne(projectId);
		User user = userRepository.findOne(userId);
		
		List<User> users = project.getUsers();
		
		if(!users.contains(user)){
			users.add(user);
			project.setUsers(users);
			super.update(project);
		}
		else{
			project = null;
		}
		
		return project;
	}


	@Override
	public Project setManager(String projectId, String userId) {
		Project project = findOne(projectId);
		User user = userRepository.findOne(userId);
		
		project.setManager(user);
		super.update(project);
		return project;
	}


	@Override
	public Project addActor(String projectId, Actor actor) {
		
		log.info("Saving actor = {}", actor);
		
		actor.setCreatedBy(getUser());
		actor.setLastUpdatedBy(getUser());

		Project project = findOne(projectId);
		List<Actor> actors = project.getActors();

		if (actors == null) {
			actors = new ArrayList<Actor>();
		}
		
		actors.add(actor);
		project.setActors(actors);
		
		log.info("Updating  project = {}", project);
		
		super.update(project);
		
		
		return project;
		
		
	}


}
